package com.wo.cloud.tenant.interceptor;

import com.wo.cloud.core.constant.TenantConstant;
import com.wo.cloud.core.context.TenantContextHolder;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author liry
 * @version 1.0
 * @date Created on 2021/4/25 11:26
 * Description: Feign 的拦截器 RequestInterceptor
 * <p>
 * SpringCloud微服务使用Feign进行服务间调用的时候可以使用 RequestInterceptor 统一拦截请求来完成设置 header 等相关请求，
 * 但 RequestInterceptor 和 ClientHttpRequestInterceptor 有点不同，它拿不到原本的请求，所以要通过其他方法来获取原本的请求
 */

@Slf4j
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class FeignTenantInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        // 获取 原请求的相关信息
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        System.out.println("request: " + request);

        if (TenantContextHolder.getTenantId() == null) {
            log.debug("TTL 中的 租户ID为空，feign拦截器 >> 跳过");
            return;
        }
        requestTemplate.header(TenantConstant.TENANT_ID_HEADER, TenantContextHolder.getTenantId().toString());
    }
}
